package com.blue.Impl.system;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blue.mapper.system.FileInfoMapper;
import com.blue.po.system.FileInfoPO;
import com.blue.service.system.IFileInfoService;
import com.blue.common.constant.CommonConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 系统文件信息表 服务实现类
 * </p>
 *
 * @author nanjie.chen
 * @since 2023-09-17
 */
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfoPO> implements IFileInfoService {

    @Value("${file.uploadPath}")
    private String uploadPath;

    @Override
    @Transactional
    public void deleteFile(List<String> ids) {
        List<FileInfoPO> fileInfoPOS = this.listByIds(ids);
        fileInfoPOS.forEach(file -> {
            File deleteFile = new File(file.getPath());
            if (deleteFile.exists()) {
                boolean delete = deleteFile.delete();
                if (!delete) {
                    throw new RuntimeException("删除系统文件失败");
                }
            }
        });
        this.removeBatchByIds(ids);
    }

    @Override
    @Transactional
    public void synchronous() {
        File file = new File(uploadPath);
        if (!file.exists()) {
            throw new RuntimeException("同步失败，系统配置上传目录不存在");
        }
        List<String> fileNames = Arrays.asList(file.list());
        List<FileInfoPO> fileInfoPOS = this.list();
        List<FileInfoPO> download = new ArrayList<>();
        List<FileInfoPO> unDownload = new ArrayList<>();
        fileInfoPOS.forEach(fileInfo -> {
            if (fileNames.contains(fileInfo.getFileName()) && CommonConstant.DISABLE.equals(fileInfo.getStatus())) {
                fileInfo.setStatus(CommonConstant.NORMAL);
                download.add(fileInfo);
            } else if (!fileNames.contains(fileInfo.getFileName()) && CommonConstant.NORMAL.equals(fileInfo.getStatus())) {
                fileInfo.setStatus(CommonConstant.DISABLE);
                unDownload.add(fileInfo);
            }
        });
        this.updateBatchById(download);
        this.updateBatchById(unDownload);
    }
}
